I have a scenario where I may not know if a certain object property is defined or not. If it is, it should be a function, and it should be called. If it is undefined, a backup function is created. I am doing this with logical ||:
// handleGetData may be undefined:
const { handleGetData, ActionCreators } = fromSomewhere;
const getData =
handleGetData ||
function () {
dispatch(
ActionCreators.GetData({
params: params
})
);
};
getData()
This seems to work just fine, except that eslint complains about an Unexpected unnamed function But the syntax breaks when I try to return an arrow function after the ||:
const getData =
handleGetData ||
() => { // <------ Parsing error: Expression expected
dispatch(
ActionCreators.GetData({
params: params
})
);
};
Why is this? If handleGetData is not defined, shouldn't the value of getData then become the arrow function, and still be callable?
Putting parantheses around the function will solve the syntax error:
const getData =
handleGetData ||
(() => {
dispatch(
ActionCreators.GetData({
params: params,
})
);
});
The eslint error is likely caused by the func-names rule (see this link for more details).
You can fix it by adding a function name, such as handleGetDataFallback:
const getData2 =
handleGetData ||
function handleGetDataFallback () {
dispatch(
ActionCreators.GetData({
params: params,
})
);
};